<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px" @keyup.enter="submitHandle()">
			<el-form-item prop="username" label="用户名">
				<el-input v-model="dataForm.username" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item prop="realName" label="姓名">
				<el-input v-model="dataForm.realName" placeholder="姓名"></el-input>
			</el-form-item>
			<el-form-item prop="gender" label="性别">
				<el-input v-model="dataForm.genderName" dict-type="user_gender"></el-input>
			</el-form-item>
			<el-form-item prop="mobile" label="手机号">
				<el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
			</el-form-item>
			<el-form-item prop="email" label="邮箱">
				<el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
			</el-form-item>
			<el-form-item prop="password" label="密码">
				<el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
			</el-form-item>
			<el-form-item prop="status" label="状态">
				<el-input v-model="dataForm.statusName" dict-type="user_status"></el-input>
			</el-form-item>
			<el-form-item v-if="dataForm.id != ''" label="头像选择">
				<img :src="dataForm.avatar" style="width: 50px; height: 50px" />
			</el-form-item>
			<el-form-item>
				<el-upload
					ref="uploadRef"
					on-change="fileChange"
					class="upload-demo"
					:http-request="uploadFiles"
					:auto-upload="false"
					limit="1"
					:on-success="handleSuccess"
					@change="fileChange"
				>
					<template #trigger>
						<el-button type="primary" class="mr-10">选择新头像</el-button>
					</template>
					<template #tip>
						<div class="el-upload__tip">图片格式为jpg/png，图片大小不得超过5MB</div>
					</template>
				</el-upload>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useOrgListApi } from '@/api/sys/orgs'
import { useUserApi, useUserSubmitApi } from '@/api/sys/user'
import constant from '@/utils/constant'
import { UploadFile, UploadFiles, UploadInstance, UploadProps } from 'element-plus'
import service from '@/utils/request'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const orgList = ref([])
const dataFormRef = ref()
const url = import.meta.env.VITE_API_URL
const def = ref(url)
const dataForm = reactive({
	id: '',
	username: '',
	realName: '',
	orgId: '',
	orgName: '',
	password: '',
	gender: 0,
	genderName: '男',
	email: '',
	mobile: '',
	roleIdList: [] as any[],
	postIdList: [] as any[],
	status: 1,
	statusName: '默认',
	avatar: ''
})

//文件改变以后触发
const fileChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	if (uploadFile.raw || new Blob()) {
		// 根据实际结构调整属性名
		const file = uploadFile.raw || new Blob()
		const reader = new FileReader()

		reader.onload = function (event: ProgressEvent<FileReader>) {
			if (event.target.readyState === FileReader.DONE) {
				dataForm.avatar = event.target.result as string
			}
		}

		reader.readAsDataURL(file)
	} else {
		console.error('无法从 uploadFile 中获取有效的 File 或 Blob 对象')
	}
}
const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (id) {
		getUser(id)
	}

	getOrgList()
	getPostList()
	getRoleList()
}

// 获取岗位列表
const getPostList = () => {
	// return usePostListApi().then(res => {
	// 	postList.value = res.data
	// })
}

// 获取角色列表
const getRoleList = () => {
	// return useRoleListApi().then(res => {
	// 	roleList.value = res.data
	// })
}

// 获取机构列表
const getOrgList = () => {
	return useOrgListApi().then(res => {
		orgList.value = res.data
	})
}

// 获取信息
const getUser = (id: number) => {
	useUserApi(id).then(res => {
		console.log('打印useUserApi', res.data)
		Object.assign(dataForm, res.data)
		dataForm.avatar = def.value + dataForm.avatar
	})
}

//上传
//上传图片
const uploadRef = ref<UploadInstance>()
const uploadFiles = async file => {
	const formData = new FormData()
	formData.append('file', file.file)
	formData.append('userId', dataForm.id)
	await service.post(constant.uploadHeadPic, formData).then(res => {
		dataForm.avatar = res.data.avatar
		uploadRef.value?.clearFiles()
	})
}

const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
	console.log('打印上传以后的信息' + JSON.stringify(res))
	dataForm.avatar = res.data.filePath
	if (res.code !== 0) {
		ElMessage.error('上传失败：' + res.msg)
		return false
	}
}
const dataRules = ref({
	username: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	realName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	mobile: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	orgId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

// 表单提交
const submitHandle = () => {
	uploadRef.value!.submit()
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		useUserSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
